package com.baseframe.system.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.mybatis.utils.PageUtil;
import com.baseframe.system.constant.BaseSystemConstant;
import com.baseframe.system.entity.BaseMenu;
import com.baseframe.system.entity.vo.BaseMenuVO;
import com.baseframe.system.service.BaseMenuService;
import com.baseframe.system.mapper.BaseMenuMapper;
import com.baseframe.tool.utils.data.BeanUtil;
import com.baseframe.tool.utils.data.NodeUtil;
import com.baseframe.tool.utils.redis.CommonRedisUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**

* @description 针对表【base_menu(菜单表)】的数据库操作Service实现
* @createDate 2023-06-20 19:19:35
*/
@Service
@AllArgsConstructor
public class BaseMenuServiceImpl extends ServiceImpl<BaseMenuMapper, BaseMenu>
    implements BaseMenuService{


    @Override
    public List<BaseMenuVO> loadingMenu() {
        //1.尝试从redis中去获取目录

        Long roleId = AuthUtil.getRoleId();
        String menuJson = CommonRedisUtil.getValue(BaseSystemConstant.MENU_REDIS_KEY + roleId);
        if (menuJson!=null){
            return JSONUtil.toList(menuJson, BaseMenuVO.class);
        }
        //2.从数据库中获取
        List<BaseMenu> baseMenuList = this.baseMapper.getMenuByRoleId(roleId);

        List<BaseMenuVO> baseMenuVOList = new ArrayList<>();

        for (BaseMenu baseMenu : baseMenuList) {
            BaseMenuVO baseMenuVO = new BaseMenuVO();
            BeanUtil.copyProperties(baseMenu,baseMenuVO);
            baseMenuVOList.add(baseMenuVO);
        }

        baseMenuVOList = NodeUtil.wrap(baseMenuVOList);
        //重新存储到redis中

        menuJson = JSONUtil.toJsonStr(baseMenuVOList);

        CommonRedisUtil.setValue(BaseSystemConstant.MENU_REDIS_KEY+roleId,menuJson);


        return baseMenuVOList;
    }

    @Override
    public Page<BaseMenuVO> menuPageList(Page<BaseMenuVO> page, String menuName) {
        page = PageUtil.selectCountPage(page);
        return this.baseMapper.menuPageList(page,menuName);
    }
}




